package cmd

import (
	"context"
	"github.com/gookit/color"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"github.com/spf13/cobra"
	"melon/server/global"
)

// versionCmd represents the version command
var uploadCmd = &cobra.Command{
	Use:   "upload",
	Short: "上传文件",
	Long:  `上传文件长信息`,
	Run: func(cmd *cobra.Command, args []string) {
		uploadFile(global.MelonYml.GetString("Custom.LocalFilename"),
			global.MelonYml.GetString("Qiniu.Bucket"),
			global.MelonYml.GetString("Custom.LocalFilename"),
			global.MelonYml.GetString("Qiniu.AccessKey"),
			global.MelonYml.GetString("Qiniu.SecretKey"))
	},
}

func init() {
	rootCmd.AddCommand(uploadCmd)
	uploadCmd.Flags().StringP("path", "p", "./config/melon.yml", "自定配置文件路径(绝对路径)")
}

func uploadFile(localFile, bucket, key, accessKey, secretKey string) {
	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}
	mac := qbox.NewMac(accessKey, secretKey)
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Zone = &storage.ZoneHuabei
	// 是否使用https域名
	cfg.UseHTTPS = true
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false
	// 构建表单上传的对象
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	err := formUploader.PutFile(context.Background(), &ret, upToken, key, localFile, nil)
	if err != nil {
		color.Error.Println(err)
		return
	}
	color.Info.Printf("Upload %s (%s) successfully\n", ret.Key, ret.Hash)

}
